require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` });
const jwt = require('jsonwebtoken')
const setToken = (user)=>  {
    //调用jwt.sifn()生成jwt字符串，三个参数分别是：用户信息对象、加密秘钥、配置对象
    const { userId, phone, username, email} = user;
    const token =  'Bearer ' + jwt.sign({
        userId,
        phone, 
        username,
        email
    }, secretKey);
    return token
}
const getToken = (token) => {
    //解密token信息
    try {
        const info = jwt.verify(token.split(' ')[1], secretKey);
        return info;
    } catch (err) {
        console.error('Failed to verify token', err);
        return null;
    }
}
function generateUserId(username) {
    // 获取当前时间戳
    const timestamp = Date.now();
  
    // 生成一个1000以内的随机数，并确保它总是3位数
    const randomNum = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  
    // 获取用户名最后两个字符的电码
    const lastTwoChars = username.slice(-2);
    const charCodes = lastTwoChars.split('').map(char => char.charCodeAt(0)).join('');
  
    // 组合成用户ID
    const userId = `${timestamp}-${randomNum}-${charCodes}`;
  
    return userId;
}


function generateVeryCode() {
    return Math.floor(Math.random() * 9000) + 1000;
}


const os = require('os');
const getIP = () => {
  // 获取所有网络接口的详细信息
  const interfaces = os.networkInterfaces();
  // 遍历每个网络接口，找到非内部且为IPv4的地址
  let ip;
  for (const name of Object.keys(interfaces)) {
    for (const alias of interfaces[name]) {
      // 排除未指定、回环和内网IP地址
      if (
        alias.family === 'IPv4' &&
        alias.address !== '127.0.0.1' &&
        !alias.internal
      ) {
        ip = alias.address;
        break;
      }
    }
  
    // 如果找到了一个有效的IP地址，就不再继续查找其他接口
    if (ip) break;
  }
  return ip;
}
/**
 * 过滤对象属性，将不用的属性剔除出去
 * input obj:{ a:1,b:2,c:3 } ,allowedKeys:[a,b]
 * output obj:{  a:1,b:2 }
 * */
function filterObjectByKeys(obj, allowedKeys) {
  if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {
      throw new TypeError('The first argument must be an object.');
  }
  if (!Array.isArray(allowedKeys)) {
      throw new TypeError('The second argument must be an array.');
  }

  return Object.fromEntries(
      Object.entries(obj).filter(([key, _]) => allowedKeys.includes(key))
  );
}
/**
 * 转换象属性，将属性改名，将下划线属性转驼峰属性
 * */
function transformPropertyNames(array, propertyMap) {
  return array.map(item => {
      const newItem = {};
      for (const key in item) {
          if (propertyMap.hasOwnProperty(key)) {
              newItem[propertyMap[key]] = item[key];
          } else {
              newItem[key] = item[key];
          }
      }
      return newItem;
  });
}


/**
 * 格式化时间成为 2024-08-03 09:20:18
 * */
function formatTime(date){
    const now = new Date(date);
    const { year, month, day, hours, minutes, seconds } = {
      year: now.getFullYear(),
      month: String(now.getMonth() + 1).padStart(2, '0'),
      day: String(now.getDate()).padStart(2, '0'),
      hours: String(now.getHours()).padStart(2, '0'),
      minutes: String(now.getMinutes()).padStart(2, '0'),
      seconds: String(now.getSeconds()).padStart(2, '0')
    };
  
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };
  

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
function handleTree(data, id, parentId, children) {
  let config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  };

  var childrenListMap = {};
  var nodeIds = {};
  var tree = [];

  for (let d of data) {
    let parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (let d of data) {
    let parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (let t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (let c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
}

module.exports={
    setToken,
    getToken,
    generateUserId,
    generateVeryCode,
    getIP,
    filterObjectByKeys,
    transformPropertyNames,
    formatTime,
    handleTree
}
   